package com.servlet;

/**
 * @author 徐洲
 * @version 1.0
 */

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @author 徐洲
 * @version 1.0
 */
@WebServlet(urlPatterns = {"/fileDownloadServlet"})
public class FileDownloadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.得到文件名和文件路径(文件资源的路径！)
        request.setCharacterEncoding("utf-8");
        String fileName = request.getParameter("name");
        String filePath = "/upload/article/" + fileName;

        //2.通过ServletContext对象得到文件的MIME类型
        String mimeType = request.getServletContext().getMimeType(filePath);
        System.out.println("mimeType = " + mimeType);

        //3.设置第一个响应头Content-Type
        response.setContentType(mimeType);

        //4.设置第二个响应头Content-Disposition
        //Content-Disposition用于指定下载的数据的展示形式，其中attachment表示使用文件下载方式
        //不同浏览器需要的编码格式不同
        if (request.getHeader("User-Agent").contains("Chrome")) {
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    URLEncoder.encode(fileName, "UTF-8"));
        } else {
            //其他浏览器的编码操作
        }

        //5.读取文件，将读取到的文件返回给客户端(IO流拷贝的封装)
        //获取与数据源文件相关联的字节输入流
        InputStream resourceAsStream = request.getServletContext().getResourceAsStream(filePath);
        //获取与目的地文件相关联的字节输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //利用封装好的工具类，进行IO流拷贝
        IOUtils.copy(resourceAsStream, outputStream);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
